//
//  AppDelegate.swift
//  frptool
//
//  Created by 傅攀 on 2019/11/20.
//  Copyright © 2019 傅攀. All rights reserved.
//

import Cocoa

import INISerialization
import INI

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var statusItem : NSStatusItem? = nil
    
    var clientPath : String? = nil
    var configPath : String? = nil
    
    var window: NSWindow? = nil
    var viewController : MainViewController = MainViewController()
    
    var frpcConfig: FRPCConfig? = nil
    
    var processManager: FRPCProcessManager? = nil
    
    lazy var mainWindowController: NSWindowController = {
        let windowVC = NSWindowController()
        return windowVC
    }()
    
    

    @IBOutlet weak var statusBarItemMenu: NSMenu!
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        clientPath = Bundle.main.path(forResource: "frpc", ofType: "")
        configPath = NSHomeDirectory() + "/Documents/frpc.ini"
        
        createButtonOnStatusBarForMenu()
        
        
        do{
            let config = try parseINI(filename: configPath!)
            
            frpcConfig = FRPCConfig(
                
                common: .init(
                    server_addr: config["common"]?["server_addr"] ?? "",
                    server_port: config["common"]?["server_port"] ?? "",
                    token: config["common"]?["token"] ?? ""
                ),
                ssh: .init(
                    type: "tcp",
                    local_ip: config["ssh"]?["local_ip"] ?? "",
                    local_port: config["ssh"]?["local_port"] ?? "",
                    remote_port: config["ssh"]?["remote_port"] ?? ""
                )
            )

        }catch let err{
            print(err.localizedDescription)
        }
       
        
        processManager = FRPCProcessManager(clientPath: clientPath!, configPath: configPath!)
        
        

        

        
       
        
        window = NSWindow()
        window?.title = "FRP工具"
        window?.styleMask = [.titled,.closable,.miniaturizable]
        window?.contentViewController = viewController
        window?.windowController = self.mainWindowController
        self.mainWindowController.window = self.window
        window?.makeKeyAndOrderFront(self)
        window?.center()
        

        
        
        
        
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
        
        processManager?.disconnect()
    }
    
    func createButtonOnStatusBarForMenu(){
        let statusBar = NSStatusBar.system
        let item = statusBar.statusItem(withLength: NSStatusItem.squareLength)
        let icon = NSImage(named: "statusIcon")
            
        item.button?.image = icon
        item.menu = self.statusBarItemMenu
        statusItem = item
    }
    
    @IBAction func showMainWindow(_ sender: Any) {
        //NSRunningApplication.current.activate(options: [NSApplication.ActivationOptions.activateIgnoringOtherApps])
                //let window =  NSApp.windows[0]
                //window.orderFront(self)
        
        
        self.window?.makeKeyAndOrderFront(self)
    }
    

    
    @IBAction func connectBtnClick(_ sender: Any) {
        
        
        processManager?.connect()
        
    }
    

    @IBAction func disconnectBtnClick(_ sender: Any) {
        processManager?.disconnect()
    }
    
    @IBAction func aboutBtnClick(_ sender: Any) {
        print("test")
    }
    
    @IBAction func quitBtnClick(_ sender: Any) {
        processManager?.disconnect()
        NSApp.terminate(self)
    }
    
    func getFrpcConfig()-> FRPCConfig?{
        return frpcConfig
    }
    
    func setFrpcConfig(frpconfig : FRPCConfig){
        self.frpcConfig = frpconfig
        
        do {
            
            let oodata = try INIEncoder().encode(self.frpcConfig!)
            
            var str = String(data: oodata, encoding: String.Encoding.utf8)
            var str2 = "";
            str?.forEach({ (c) in
                if(c != "\""){
                    str2.append(c)
                }
            })
       
            if !FileManager().fileExists(atPath: configPath!) {
                FileManager().createFile(atPath: configPath!,contents: nil,attributes: nil)
            }
           
            
            try str2.write(toFile:configPath!, atomically: false, encoding: .utf8)

            
        } catch let err {
            print(err.localizedDescription)
        }
    }
    
    
    func getClientPath() -> String{
        return clientPath!
    }
    
    
    func getConfigPath() -> String {
        return configPath!
    }
    
    
    func getProcessManager() -> FRPCProcessManager{
        return processManager!
    }
    
    
    func activeStatusBarIcon(){
        let icon = NSImage(named: "statusIconActive")
        statusItem?.button?.image = icon
    }
    
    func inactiveStatusBarIcon(){
        let icon = NSImage(named: "statusIcon")
        statusItem?.button?.image = icon
    }
    
}

